package com.sixth.shiro;

import com.sixth.bean.*;
import com.sixth.constant.Constant;
import com.sixth.mapper.MarketAdminMapper;
import com.sixth.mapper.MarketRoleMapper;
import com.sixth.mapper.MarketUserMapper;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/**
 * @ClassName ShiroRealm
 * @Description TODO
 * @Author XiaoWJ
 * @Date 2022/9/9 9:33
 **/

//@Component
public class ShiroRealm extends AuthorizingRealm {

    @Autowired
    MarketAdminMapper marketAdminMapper;

    @Autowired
    MarketRoleMapper marketRoleMapper;

    @Autowired
    MarketUserMapper marketUserMapper;

    // 获得认证数据
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        MarketToken marketToken = (MarketToken) authenticationToken;

        // 获得需要认证的用户名

        SimpleAuthenticationInfo simpleAuthenticationInfo = null;
        // 判断登录的类型
        if (Constant.ADMIN_LOGIN.equals(marketToken.getType())) {
            simpleAuthenticationInfo = getSimpleAuthenticationInfoOfMarketAdmin(marketToken);
        }

        if (Constant.WX_LOGIN.equals(marketToken.getType())) {
            simpleAuthenticationInfo = getSimpleAuthenticationInfoOfMarketUser(marketToken);
        }

        /*// 在数据库中查询该用户对应的密码
        List<MarketAdmin> admins = selectMarketAdminByUsername(username);

        MarketAdmin marketAdmin = null;
        if (admins.size() == 1){
            marketAdmin = admins.get(0);
        }
        // 返回认证消息，其中第一个参数是principal信息
        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(marketAdmin, marketAdmin.getPassword(), this.getName());*/


        return simpleAuthenticationInfo;
    }

    // 获得授权数据
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        MarketAdmin principal = (MarketAdmin) principalCollection.getPrimaryPrincipal();

        // 数据库中查询该用户的权限信息
        List<String> permissions = selectPermissionsByMarketAdmin(principal);

        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();

        authorizationInfo.addStringPermissions(permissions);

        return authorizationInfo;
    }


    private SimpleAuthenticationInfo getSimpleAuthenticationInfoOfMarketAdmin(MarketToken marketToken) {
        MarketAdminExample example = new MarketAdminExample();
        MarketAdminExample.Criteria criteria = example.createCriteria();

        criteria.andUsernameEqualTo(marketToken.getUsername()).andDeletedEqualTo(false);

        List<MarketAdmin> admins = marketAdminMapper.selectByExample(example);

        if (admins.size() == 0) {
            throw new UnknownAccountException("用户名或密码错误！");
        }

        MarketAdmin marketAdmin = admins.get(0);


        return new SimpleAuthenticationInfo(marketAdmin, marketAdmin.getPassword(),new MyByteSource(marketAdmin.getUsername()),this.getName());


    }

    private SimpleAuthenticationInfo getSimpleAuthenticationInfoOfMarketUser(MarketToken marketToken) {
        MarketUserExample example = new MarketUserExample();
        MarketUserExample.Criteria criteria = example.createCriteria();

        criteria.andUsernameEqualTo(marketToken.getUsername());

        List<MarketUser> marketUsers = marketUserMapper.selectByExample(example);

        if (marketUsers.size() == 0) {
            throw new UnknownAccountException("用户名或密码错误！");
        }

        MarketUser marketUser = marketUsers.get(0);

        String s = new String(marketToken.getPassword());
        System.out.println(s);
        System.out.println(marketUser.getPassword());

        // 用户状态为1，锁定
        if (marketUser.getStatus() == (byte)1) {
            throw new LockedAccountException("账号已被禁用,请联系管理员！");
        }

        return new SimpleAuthenticationInfo(marketUser, marketUser.getPassword(),new MyByteSource(marketUser.getUsername()), this.getName());


    }


    // TODO 数据库中查询密码和授权信息

    private List<MarketAdmin> selectMarketAdminByUsername(String username) {
        MarketAdminExample example = new MarketAdminExample();

        MarketAdminExample.Criteria criteria = example.createCriteria();

        criteria.andUsernameEqualTo(username);

        List<MarketAdmin> admins = marketAdminMapper.selectByExample(example);

        return admins;
    }


    private List<String> selectPermissionsByMarketAdmin(MarketAdmin marketAdmin) {

        // 获得角色信息
        Integer[] roleIds = marketAdmin.getRoleIds();

        // 从角色表联系权限表查出所有去重权限
        List<String> permissions = selectPermissionsByRoles(roleIds);

        return permissions;

    }

    private List<String> selectPermissionsByRoles(Integer[] roleIds) {
        List<String> permissions = null;

        for (Integer roleId : roleIds) {
            if (roleId == 1) {
                permissions = marketRoleMapper.selectAllPermissions();
                return permissions;
            }
        }
        return marketRoleMapper.selectPermissionsByRole(roleIds);


    }

}
